package com.example.cardgame

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

const val THIRD_IMAGE1 = "THIRD_BACKGROUND_IMAGE"
//bug点：
//点击拍摄按钮弹出界面，但是不拍照直接返回，结果返回前端页面为空
//或者直接不执行拍摄这个事件，返回到钱一个页面也是空
class test_second : AppCompatActivity() {
    private var thirdImageUri: Uri? = null
    private lateinit var takePictureLauncher: ActivityResultLauncher<Intent>

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.test_second)


        val sharedPreferences = getSharedPreferences("app_prefs", MODE_PRIVATE)

        // 拍摄照片初始化
        takePictureLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                // 用户成功拍照，更新图片 URI
                thirdImageUri?.let {
                    findViewById<ImageView>(R.id.imageView).setImageURI(it)
                }
            }else {
                Toast.makeText(this, "拍摄取消", Toast.LENGTH_SHORT).show()
            }
        }


        // 加载上一个页面传过来的
        val usernameHint = intent.getStringExtra("username") ?: ""
        val snoHint = intent.getStringExtra("sno") ?: ""
        val phoneNumberHint = intent.getStringExtra("phoneNumber") ?: ""
        val emailHint = intent.getStringExtra("email") ?: ""
        // 加载最近一张的头像
        val currentUriString = intent.getStringExtra("currentUri")
        // 修改文本默认值
        findViewById<EditText>(R.id.username).hint = usernameHint
        findViewById<EditText>(R.id.sno).hint = snoHint
        findViewById<EditText>(R.id.phoneNumber).hint = phoneNumberHint
        findViewById<EditText>(R.id.editTextTextEmailAddress).hint = emailHint

        thirdImageUri = currentUriString?.let { Uri.parse(it) }

        // 显示头像
        thirdImageUri?.let {
            findViewById<ImageView>(R.id.imageView).setImageURI(it)
        }
        val confirm: Button = findViewById(R.id.confirm)
        val buttonPhoto: ImageButton = findViewById(R.id.photo)

        // 隐式intent调用拍摄
        buttonPhoto.setOnClickListener {
            dispatchTakePictureIntent()
        }

        // 返回
        confirm.setOnClickListener {
            val username = findViewById<EditText>(R.id.username).text.toString()
            val sno = findViewById<EditText>(R.id.sno).text.toString()
            val phoneNumber = findViewById<EditText>(R.id.phoneNumber).text.toString()
            val email = findViewById<EditText>(R.id.editTextTextEmailAddress).text.toString()

            // 性别
            val genderGroup: RadioGroup = findViewById(R.id.genderRadioGroup)
            val selectedGenderId: Int = genderGroup.checkedRadioButtonId
            val gender: String = if (selectedGenderId != -1) {
                findViewById<RadioButton>(selectedGenderId).text.toString()
            } else {
                ""
            }

            //爱好
            val hobbies = arrayListOf<String>()
            if (findViewById<CheckBox>(R.id.checkBox).isChecked) hobbies.add("唱歌")
            if (findViewById<CheckBox>(R.id.checkBox2).isChecked) hobbies.add("看电影")
            if (findViewById<CheckBox>(R.id.checkBox3).isChecked) hobbies.add("打游戏")
            if (findViewById<CheckBox>(R.id.checkBox4).isChecked) hobbies.add("其他")

            val intent = Intent()
            // 使用当前的头像 URI，只有在拍照成功后才更新
            val imageUriString = thirdImageUri?.toString() ?: currentUriString ?: ""
            intent.putExtra("userInfo", arrayOf(username, sno, phoneNumber, email, gender, imageUriString, *hobbies.toTypedArray()))

            with(sharedPreferences.edit()) {
                putString(THIRD_IMAGE1, thirdImageUri.toString())
                apply()
            }
            setResult(6, intent)
            finish()
        }


    }
    private fun dispatchTakePictureIntent() {
        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (takePictureIntent.resolveActivity(packageManager) != null) {
            // 创建文件并获取 URI
            val photoFile: File? = createImageFile()
            photoFile?.also {
                thirdImageUri = FileProvider.getUriForFile(this,
                    "${packageName}.fileprovider", it)
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, thirdImageUri)
                takePictureLauncher.launch(takePictureIntent)
            }
        }
    }
    private fun createImageFile(): File {
        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
        val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile("JPEG_${timeStamp}_", ".jpg", storageDir)
    }

}


